var zTree,rMenu,key,demoIframe,setting;
var addCount = 1,build=false;
var lastValue = "", nodeList = [], fontCss = {color:"blue", "font-weight":"bold"};
var menu = document.querySelector('.menu');
var orgDeviceTypeMap = new Map(); //存放设备类型字典

var parkOrgTreeJs = function(targetObj){
	this.sysUtils = new kendoUtils();
	this.targetObj = targetObj;
	this.init();
	zTree = $.fn.zTree.init(targetObj.find("#tree"), setting);
    buildTree=$.fn.zTree.init(targetObj.find("#tree"), setting);
	return this;
};

parkOrgTreeJs.prototype={
		init:function(){
			var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj.find(".search-panel"));
			var bindFunctionArray = [];
			this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
			this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
			this.showMask();
			this.loadtree();
			this.loadEqButton();
			demoIframe = $(".resource-panel");
			demoIframe.bind("load", this.loadReady);
			rMenu = $("#rMenu");
			key = $("#key");
			key.bind("focus", this.focusKey)
			.bind("blur", this.blurKey)
			.bind("propertychange", this.searchNode)
			.bind("input", this.searchNode);
			$("#collapseAllBtn").bind("click", {type:"collapseAll",id:"collapseAllBtn"}, this.expandNode);
			$("#expandAllBtn").bind("click", {type:"expandAll",id:"expandAllBtn"}, this.expandNode);
			$("#addPar button").bind("click",{type:"par"}, this.addTreeNode);
			$("#addWsn button").bind("click",{type:"wsn"}, this.addTreeNode);
			$("#addChnin button").bind("click",{type:"chn_in"}, this.addTreeNode);
			$("#addChnout button").bind("click",{type:"chn_out"}, this.addTreeNode);
//			$("#addEqu button").bind("click",{type:"equ"}, this.addTreeNode);
			$("#editNode button").bind("click",{type:"edit"}, this.editTreeNode);
			$("#renameNode button").bind("click",{type:"rename"}, this.renameTreeNode);
			$("#removeNode button").bind("click",{type:"remove"}, this.removeTreeNode);
			$("#refresh button").bind("click",{type:"refresh"}, this.resetTree);
			/* var carOpions = Utils.getModelValueByModelKey(BASIS.VEHICLE_TYPE.COMPACT);	
            Utils.createDataDictDropDownList([{div:this.targetObj.find("#carType"),parentModelKey:BASIS.VEHICLE_TYPE.ROOT,select:carOpions}],this);*/
		},
		/**
		 * 加载设备右键按钮(二级菜单)
		 */
		loadEqButton:function(){
			var that = this;
			var identVideo = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_0);
			var envirVideo = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_1);
			var control = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_3);
			var addEquLower = that.targetObj.find("#addEquLower");     //通道下的添加通道二级菜单
			var addEquLowerE = that.targetObj.find("#addEquLowerE");   //设备下的添加设备二级菜单
			var addEquLowerP = that.targetObj.find("#addEquLowerP");   //设备下的添加分区二级菜单
			JsonpAjax(baseApiPath+"facilities/devices",null,"json",function(result){
				$(result).each(function(){
					orgDeviceTypeMap.put(this.deviceType, this);
					if(this.sFlag == 0){

						var li = $('<li class="menu-item"><button type="button" class="menu-btn"><span class="menu-text">'+this.deviceName+'</span></button></li>');
						li.data("devJson",this);
						//添加点击按钮事件
						li.bind("click",{type:"equ"}, that.addTreeNode);
						//添加通道下的右键按钮 (所有设备均可添加到通道下面)
						addEquLower.append(li);
						//添加设备下的右键按钮   主控板和摄像机不能添加到设备下面
						if(this.deviceCategories != identVideo && this.deviceCategories!=envirVideo
								&& this.deviceCategories!=control){
							addEquLowerE.append(li.clone(true));
							if(this.deviceType=='9'){//分区余位显示屏
                                addEquLowerP.append(li.clone(true));
							}
						}
					}
				});

			});
		},
		//树加载
		loadtree:function () {
			setting = {
					view: {
						dblClickExpand: true,
						showLine: true,
						selectedMulti: false,
						fontCss: this.getFontCss,

					},
					data: {
						simpleData: {
							enable:true,
							idKey: "id",
							pIdKey: "pId",
							rootPId: ""
						}
					},
					async: {
						enable: true,
						type:"post",
						url:baseApiPath+"facilities/ztreeData",
						dataFilter: this.filter
					},
					callback: {
						beforeClick: this.BeforeClick,
						onRightClick: this.OnRightClick,
						onAsyncSuccess: this.zTreeOnAsyncSuccess
					},

			};
			zTree = $.fn.zTree.init(this.targetObj.find("#tree"), setting);

		},
		BeforeClick:function(treeId, treeNode) {
			parkTree.showMask();
			zTree ==null?$.fn.zTree.init(parkTree.targetObj.find("#tree"), setting): $.fn.zTree.getZTreeObj("tree");
			var gpc = treeNode.gpc;
			if(gpc == 'chn_in' || gpc == 'chn_out'){
				gpc = 'chn';
			}
			var pathName = treeNode.pathName.replaceAll(',','<span style="font-size: 20px; color: #2184bb;padding: 0 10px;font-weight: bold;">&gt;</span>');
			setTimeout(function() {
				parkTree.loadContent(gpc,pathName,treeNode);
			},300);
			/*if (treeNode.isParent) {
             /!*if (treeNode.isParent && treeNode.level >0) {*!/
             zTree.expandNode(treeNode);
             return false;
             } else {
             demoIframe.attr("src",treeNode.file + ".html");
             return true;
             }*/
		},

		OnRightClick:function (event, treeId, treeNode) {//右键
			if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
				//zTree.cancelSelectedNode();
				parkTree.showRMenu(null, event.clientX, event.clientY);
			} else if (treeNode && !treeNode.noR) {
				zTree.selectNode(treeNode);
				parkTree.showRMenu(treeNode, event.clientX, event.clientY);
			}
		},
		showRMenu:function(treeNode, x, y) {//显示右键菜单
			if(!treeNode){
				$("#addPar").show();
				$("#addWsn").hide();
				$("#addChnin").hide();
				$("#addChnout").hide();
				$("#addEqu").hide();
				$("#removeNode").hide();
			}else{
				var type = treeNode.gpc;
				if (type=="park") {
					$("#addPar").show();
					$("#addWsn").hide();
					$("#addChnin").hide();
					$("#addChnout").hide();
					$("#addEqu").hide();
					$("#removeNode").hide();
				} else if(type=="par"){
					var nodes = treeNode.getPath();
					var wsnTF = false,parCout=0;

					for(var i=0;i<nodes.length;i++){
						if(nodes[i].gpc == 'wsn'){
							wsnTF = true;
						}else if(nodes[i].gpc == 'par'){
							parCout +=1;
						}
					}
					if(!wsnTF){
						$("#addWsn").show();
						$("#addChnin").hide();
						$("#addChnout").hide();
					}else{
						$("#addWsn").hide();
						$("#addChnin").show();
						$("#addChnout").show();
					}
					if(parCout<2){//限制同路径分区个数
						$("#addPar").show();
					}else{
						$("#addPar").hide();
					}
                    var addEqu = this.targetObj.find("#addEqu");//.find(".menu-btn");
                    if(addEqu.find("#addEquLowerP").length <= 0){
                        addEqu.find("#addEquLower").remove();
                        addEqu.find("#addEquLowerE").remove();
                        addEqu.append(this.targetObj.find("#addEquLowerP").clone(true));
                    }
					$("#removeNode").show();
				}else if(type=="wsn"){
					$("#addPar").show();
					$("#addWsn").hide();
					$("#addChnin").show();
					$("#addChnout").show();
					$("#addEqu").hide();
					$("#removeNode").show();
				}else if(type == 'equ'){
					//如果上级节点为设备，则不能在增加任何东西
					$("#addPar").hide();
					$("#addWsn").hide();
					$("#addChnin").hide();
					$("#addChnout").hide();
					$("#addEqu").hide();
					$("#removeNode").show();
					var deviceTypeJson = orgDeviceTypeMap.get(treeNode.deviceType);
					if(isNotEmpt(deviceTypeJson)){
						var control = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_3);
						if('equ' != treeNode.getParentNode().gpc && deviceTypeJson["deviceCategories"] == control){
							$("#addEqu").show();
							var addEqu = this.targetObj.find("#addEqu");//.find(".menu-btn");
							if(addEqu.find("#addEquLowerE").length <= 0){
								addEqu.find("#addEquLower").remove();
								addEqu.find("#addEquLowerP").remove();
								addEqu.append(this.targetObj.find("#addEquLowerE").clone(true));
							}
						}
					}
				}else if(type == 'chn_in' || type == 'chn_out'){
					$("#addPar").hide();
					$("#addWsn").hide();
					$("#addChnin").hide();
					$("#addChnout").hide();
					$("#addEqu").show();
					var addEqu = this.targetObj.find("#addEqu");//.find(".menu-btn");
					if(addEqu.find("#addEquLower").length <= 0){
						addEqu.find("#addEquLowerE").remove();
                        addEqu.find("#addEquLowerP").remove();
						addEqu.append(this.targetObj.find("#addEquLower").clone(true));
					}
					$("#removeNode").show();
				}

			}
			menu.style.left = x + 'px';
			menu.style.top = y + 'px';
			menu.classList.add('show-menu');
			$("body").bind("mousedown", parkTree.onBodyMouseDown);
		},
		hideMenu:function () {//隐藏右键菜单
			menu.classList.remove('show-menu');
		},
		onBodyMouseDown:function (e) {
			if (!(event.target.id == "menu" || $(event.target).parents(".menu").length>0)) {
				parkTree.hideMenu();
			}
		},
		addTreeNode:function (e) {//增加节点
			parkTree.showMask();
			parkTree.hideMenu();
			var gpc = e.data.type;
			var name ='',pid;
			if(gpc=='par'){
				name = '分区';
			}else if(gpc=='wsn'){
				name = '工作站';
			}else if(gpc=='chn_in') {
				name = '入口';
			}else if(gpc=='chn_out'){
				name = '出口';
			}else if(gpc=='equ'){
				name = '设备';
			}
			var devJson = $(this).data("devJson");
			parkTree.downDevJson = devJson;
			var newNode = { name:name + (addCount++)};
			newNode.gpc = gpc;
			newNode.iconSkin = gpc;
			var selectNodes = zTree.getSelectedNodes()[0];
			if (selectNodes) {
				newNode.checked = selectNodes.checked;
				newNode.pathName = selectNodes.pathName+','+newNode.name;
				if(devJson){
					newNode.deviceType = devJson.deviceType;
				}
				pid = selectNodes.id;
				if(!pid){
					notification({ title:"操作失败",message:"请先保存当前节点信息,然后才能新增下级节点"},'info');
					return;
				}
				newNode = zTree.addNodes(selectNodes, newNode);
			} else {
				newNode.pathName = zTree.getNodeByTId("tree_1").pathName+','+newNode.name;
				newNode = zTree.addNodes(zTree.getNodeByTId("tree_1"), newNode);
				pid = zTree.getNodeByTId("tree_1").id;
			}
			zTree.selectNode(newNode[0]);
			if(gpc == 'chn_in' || gpc == 'chn_out'){
				gpc = 'chn';
			}else if(gpc == "equ"){ //设备分很多种种类所以要特殊处理下
				gpc = parkTree.getHtmlSuffix(devJson,gpc);
			}
			var pathName = newNode[0].pathName.replaceAll(',','<span style="font-size: 20px; color: #2184bb;padding: 0 10px;font-weight: bold;">&gt;</span>');

			$("#ConentDiv").load('views/parkLotCenter/facilitiesManage/parkOrg'+gpc+'.html',function(responseTxt,statusTxt,xhr){
				if(statusTxt=="success")
					$("#titleBar").html(pathName);
				if(statusTxt=="error")
					layer.msg("Error: "+xhr.status+": "+xhr.statusText);
			});
		},


		/**
		 * 根据树形节点类型获取html后缀
		 */
		getHtmlSuffix:function(devJson,gpc){
			var voideS = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_0);
			var voideH = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_1);
			var display = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_2);
			var control = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_3);
			if(devJson["deviceCategories"] == voideS || devJson["deviceCategories"] == voideH){  //识别相机、环境相机
				gpc = gpc + "_video";
			}else if(devJson["deviceCategories"] == display){   //显示屏
				gpc = gpc + "_displayScreen";
			}else if(devJson["deviceCategories"] == control){    //主控板
				gpc = gpc + "_controlBoard";
			}else{
				gpc = gpc + "_"+devJson["deviceType"];
			}
			return gpc;
		},
		removeTreeNode:function () {//移除节点
			parkTree.hideMenu();
			var nodes = zTree.getSelectedNodes();
			if (nodes && nodes.length>0) {
				if (nodes[0].children && nodes[0].children.length > 0) {
					notification({ title:"删除失败", message:"请先删除下级数据"}, 'info');
				} else {
					var id = nodes[0].id;
					notification({title:"确认信息", message:"确定删除选中数据？"}, 'confirm', {
						callback : function(){
							$.ajax({
								url : baseApiPath + "facilities/deleteNode",
								type : "post",
								data : {"organizationCode" : id},
								dataType : "json",
								success : function(res) {
									if (res != "") {
										notification({ title:"删除成功", message:" {"+nodes[0].name+"}已删除"},'info');
										zTree.removeNode(nodes[0]);
									}
								},
								error : function() {
									notification({ title:"删除失败", message:"请检查联网状态"}, 'info');
								}
							});
						}
					});
				}
			}
		},
		checkTreeNode:function (checked) {
			var nodes = zTree.getSelectedNodes();
			if (nodes && nodes.length>0) {
				zTree.checkNode(nodes[0], checked, true);
			}
			parkTree.hideMenu();
		},
		resetTree:function () {//恢复tree
			parkTree.hideMenu();
			zTree =$.fn.zTree.init(parkTree.targetObj.find("#tree"), setting);
		},
		localUpdate:function (result) {//新增节点保存后更新树节点及导航标识
			var node = zTree.getSelectedNodes()[0];
			node.name=result.organizationName;
			node.id=result.organizationCode;
			var pathName = node.pathName.substr(0,node.pathName.lastIndexOf(',')+1)+result.organizationName;
			node.pathName = pathName;
			zTree.updateNode(node);

			pathName = pathName.replaceAll(',','<span style="font-size: 20px; color: #2184bb;padding: 0 10px;font-weight: bold;">&gt;</span>');
			$("#titleBar").html(pathName);
		},
		expandNode:function (e) {//节点展开 折叠
			zTree ==null?$.fn.zTree.init(parkTree.targetObj.find("#tree"), setting): $.fn.zTree.getZTreeObj("tree");
			type = e.data.type,
			cid = e.data.id,
			nodes = zTree.getSelectedNodes();
			$(".tree-button a").each(function () {
				if(this.id == cid){
					this.className = "select";
				}else{
					this.className ='';
				}
			});
			if (type.indexOf("All")<0 && nodes.length == 0) {
				notification({ title:"操作失败",message:"请先选择一个父节点!!"},'info');
			}

			if (type == "expandAll") {
				zTree.expandAll(true);
			} else if (type == "collapseAll") {
				zTree.expandAll(false);
			} else {
				var callbackFlag = $("#callbackTrigger").attr("checked");
				for (var i=0, l=nodes.length; i<l; i++) {
					zTree.setting.view.fontCss = {};
					if (type == "expand") {
						zTree.expandNode(nodes[i], true, null, null, callbackFlag);
					} else if (type == "collapse") {
						zTree.expandNode(nodes[i], false, null, null, callbackFlag);
					} else if (type == "toggle") {
						zTree.expandNode(nodes[i], null, null, null, callbackFlag);
					} else if (type == "expandSon") {
						zTree.expandNode(nodes[i], true, true, null, callbackFlag);
					} else if (type == "collapseSon") {
						zTree.expandNode(nodes[i], false, true, null, callbackFlag);
					}
				}
			}
		},
		focusKey:function(e){
			if (key.hasClass("empty")) {
				key.removeClass("empty");
			}
		},
		blurKey:function(e){
			if (key.get(0).value === "") {
				key.addClass("empty");
			}
		},
		setswitchCss:function (e) {
			var that = this;
			that.targetObj.find(".checkbox input[type='checkbox']").each(function () {
				if(this.value == 1){
					this.className='';
				}else{
					this.className='';
				}
			});
		},
		clickSwitch:function () {

		},
		searchNode:function(e){//根据值模糊搜索
			zTree ==null?$.fn.zTree.init(parkTree.targetObj.find("#tree"), setting): $.fn.zTree.getZTreeObj("tree");
			var views = zTree.setting.view;
			views["fontCss"] = parkTree.getFontCss;
			var value = $.trim(key.get(0).value);
			parkTree.setColor('name',value);


			zTree.expandAll(true);
			var keyType = "name";
			if (key.hasClass("empty")) {
				value = "";
			}
			if (lastValue === value) return;
			lastValue = value;
			if (value === "") return;
			//parkTree.updateNodes(false);

			//nodeList = zTree.getNodesByParamFuzzy(keyType, value);
			//parkTree.updateNodes(true);
		},
		updateNodes:function(highlight) {//更新节点
			zTree ==null?$.fn.zTree.init(parkTree.targetObj.find("#tree"), setting): $.fn.zTree.getZTreeObj("tree");
			var allNode = zTree.transformToArray(zTree.getNodes());
			for(var i=0,l=allNode.length;i<l;i++){
				allNode[i].highlight = false;
				zTree.updateNode(allNode[i]);
			}
			for( var i=0, l=nodeList.length; i<l; i++) {
				//nodeList[i].highlight = highlight;
				//zTree.updateNode(nodeList[i]);
				var array = nodeList[i].getPath();
				for(var a=0,b=array.length;a<b;a++){
					array[a].highlight = highlight;
					zTree.updateNode(array[a]);
				}
			}
			parkTree.nodeView();
		},
		nodeView:function () {
			var that = this;
			zTree ==null?$.fn.zTree.init(parkTree.targetObj.find("#tree"), setting): $.fn.zTree.getZTreeObj("tree");
			var allNode = zTree.transformToArray(zTree.getNodes());

			for(var i=0,l=allNode.length;i<l;i++){
				if(nodeList && nodeList.length > 0 ){
					/*for(var a=0,b=nodeList.length;a<b;a++){
                    if(nodeList[a].id == allNode[i].id){
                        allNode[i].highlight=true;
                    }else{
                        allNode[i].highlight=false;
                    }
                }*/
					if(!allNode[i].highlight){
						that.targetObj.find('#'+allNode[i].tId).hide();
					}else{
						that.targetObj.find('#'+allNode[i].tId).show();
					}
				}else{
					allNode[i].highlight=false;
					that.targetObj.find('#'+allNode[i].tId).hide();
				}

			}
		},
		getFontCss:function(treeId, treeNode) {
			return (!!treeNode.highlight) ? {color:"#0000FF", "font-weight":"bold","font-size":"14px"} : {color:"#000", "font-weight":"normal"};
		},
		reSetFontCss:function (treeId, treeNode) {
			return (!treeNode.highlight)?{color:"#000000", "font-weight":"normal"}:{};
		},
		setColor:function (key,value) {
			var that = this;
			zTree ==null?$.fn.zTree.init(parkTree.targetObj.find("#tree"), setting): $.fn.zTree.getZTreeObj("tree");
			nodeList = zTree.getNodesByParamFuzzy(key, value);
			if(value != ""){
				parkTree.updateNodes(true);
			}else{
				var views = zTree.setting.view;
				views["fontCss"] = parkTree.reSetFontCss;
				zTree.refresh();
			}
			if(nodeList && nodeList.length == 0){
				that.targetObj.find('#tips').show();
			}else{
				that.targetObj.find('#tips').hide();
			}
		},
		filter:function(treeId, parentNode, responseData){

			return JSON.parse(responseData.results);
		},
		zTreeOnAsyncSuccess:function (event, treeId, treeNode, msg) {//捕获异步加载正常结束的事件回调函数
			zTree ==null?$.fn.zTree.init(parkTree.targetObj.find("#tree"), setting): $.fn.zTree.getZTreeObj("tree");
			$('#tree').append('<div style="width:100%;height:430px;"></div>');
			zTree.expandAll(true);//甭管你多牛逼,都给我展开
			var content = $("#ConentDiv").html();
			if(/^\s*?$/.test(content)){
				$("#ConentDiv").load('views/parkLotCenter/facilitiesManage/parkOrgpark.html');
				var pathName = zTree.getNodeByTId("tree_1").pathName;
				zTree.selectNode(zTree.getNodeByTId("tree_1"));
				$("#titleBar").html(pathName);
			}
		},
		dblClickExpand:function(treeId, treeNode){//双击节点事件
			return treeNode.level > 0;
		},
		loadReady:function(){
			var bodyH = demoIframe.contents().find(".tree-structure").get(0).scrollHeight,
			htmlH = demoIframe.contents().find("#parkTreeManageDiv").get(0).scrollHeight,
			maxH = Math.max(bodyH, htmlH), minH = Math.min(bodyH, htmlH),
			h = demoIframe.height() >= maxH ? minH:maxH ;
			if (h < 530) h = 530;
			demoIframe.height(h);
		},
		editTreeNode:function (e) {
			if(zTree.getSelectedNodes()[0]){
				var id = zTree.getSelectedNodes()[0].id;
			}
			parkTree.hideMenu();
		},
		loadContent:function (gpc,pathName,treeNode) {
			if(gpc == "equ"){ //设备分很多种种类所以要特殊处理下
				parkTree.downDevJson = orgDeviceTypeMap.get(treeNode.deviceType);
				gpc = parkTree.getHtmlSuffix(parkTree.downDevJson,gpc);
			}
			$("#ConentDiv").load('views/parkLotCenter/facilitiesManage/parkOrg'+gpc+'.html?'+new Date().getTime(),function(responseTxt,statusTxt,xhr){
				if(statusTxt=="success")
					$("#titleBar").html(pathName);
				if(statusTxt=="error")
					layer.msg("Error: "+xhr.status+": "+xhr.statusText);
			});
		},
		showMask:function () {//显示遮罩
			var that = this;
			/*this.targetObj.find("#mask").css("height",$(document).height());
        this.targetObj.find("#mask").css("width",$(document).width());
        this.targetObj.find("#mask").show();*/
			that.targetObj.find('.resource-panel').block({ message: '<h1><img src="images/indicator_circle_thickbox.gif" /></h1>' });
		},
		hideMask:function () {
			var that = this;
			that.targetObj.find('.resource-panel').unblock();
			/*that.targetObj.find("#mask").hide();*/

		}

}
